using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using AF.Data;
using AF.Models;

namespace AF.Activities
{
    [Activity(Label = "项目详情", Theme = "@android:style/Theme.Material.Light.NoActionBar")]
    public class ProjectDetailActivity : Activity
    {
        private DatabaseHelper? dbHelper;
        private TextView? textProjectTitle;
        private TextView? textDetailIncome;
        private TextView? textDetailExpense;
        private TextView? textDetailBalance;
        private TextView? textRecordCount;
        private ListView? listViewProjectTransactions;
        private TextView? textEmptyTransactions;

        private int projectId;
        private string projectName = "";
        private List<Transaction> transactions = new List<Transaction>();

        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_project_detail);

            dbHelper = new DatabaseHelper(this);

            // 获取传入的项目ID和名称
            projectId = Intent?.GetIntExtra("project_id", -1) ?? -1;
            projectName = Intent?.GetStringExtra("project_name") ?? "项目详情";

            InitializeViews();
            SetupEventHandlers();
            LoadProjectDetail();
        }

        private void InitializeViews()
        {
            textProjectTitle = FindViewById<TextView>(Resource.Id.textProjectTitle);
            textDetailIncome = FindViewById<TextView>(Resource.Id.textDetailIncome);
            textDetailExpense = FindViewById<TextView>(Resource.Id.textDetailExpense);
            textDetailBalance = FindViewById<TextView>(Resource.Id.textDetailBalance);
            textRecordCount = FindViewById<TextView>(Resource.Id.textRecordCount);
            listViewProjectTransactions = FindViewById<ListView>(Resource.Id.listViewProjectTransactions);
            textEmptyTransactions = FindViewById<TextView>(Resource.Id.textEmptyTransactions);

            if (textProjectTitle != null)
                textProjectTitle.Text = projectName;
        }

        private void SetupEventHandlers()
        {
            if (listViewProjectTransactions != null)
            {
                listViewProjectTransactions.ItemClick += (s, e) =>
                {
                    var transaction = transactions[e.Position];
                    ShowTransactionDetails(transaction);
                };
            }
        }

        private void LoadProjectDetail()
        {
            if (dbHelper == null || projectId == -1) return;

            // 获取项目统计
            var (income, expense, balance, count) = dbHelper.GetProjectStatistics(projectId);

            if (textDetailIncome != null)
                textDetailIncome.Text = $"¥{income:N2}";

            if (textDetailExpense != null)
                textDetailExpense.Text = $"¥{expense:N2}";

            if (textDetailBalance != null)
                textDetailBalance.Text = $"¥{balance:N2}";

            if (textRecordCount != null)
                textRecordCount.Text = $"共{count}条";

            // 获取项目交易记录
            transactions = dbHelper.GetTransactionsByProject(projectId);

            if (listViewProjectTransactions != null && textEmptyTransactions != null)
            {
                if (transactions.Count > 0)
                {
                    listViewProjectTransactions.Visibility = ViewStates.Visible;
                    textEmptyTransactions.Visibility = ViewStates.Gone;

                    var adapter = new TransactionAdapter(this, transactions);
                    listViewProjectTransactions.Adapter = adapter;
                }
                else
                {
                    listViewProjectTransactions.Visibility = ViewStates.Gone;
                    textEmptyTransactions.Visibility = ViewStates.Visible;
                }
            }
        }

        private void ShowTransactionDetails(Transaction transaction)
        {
            string typeText = transaction.Type == TransactionType.Income ? "收入" : "支出";
            string message = $"类型：{typeText}\n" +
                           $"金额：¥{transaction.Amount:N2}\n" +
                           $"分类：{transaction.CategoryName}\n" +
                           $"描述：{transaction.Description}\n" +
                           $"日期：{transaction.Date:yyyy-MM-dd HH:mm}\n" +
                           $"备注：{transaction.Remark ?? "无"}";

            new AlertDialog.Builder(this)!
                .SetTitle("交易详情")!
                .SetMessage(message)!
                .SetPositiveButton("确定", (s, e) => { })!
                .Show();
        }
    }

    public class TransactionAdapter : BaseAdapter<Transaction>
    {
        private readonly Activity context;
        private readonly List<Transaction> items;

        public TransactionAdapter(Activity context, List<Transaction> items)
        {
            this.context = context;
            this.items = items;
        }

        public override Transaction this[int position] => items[position];

        public override int Count => items.Count;

        public override long GetItemId(int position) => position;

        public override View? GetView(int position, View? convertView, ViewGroup? parent)
        {
            var view = convertView ?? context.LayoutInflater.Inflate(
                Resource.Layout.list_item_transaction, null);

            var transaction = items[position];

            var textCategoryIcon = view?.FindViewById<TextView>(Resource.Id.textCategoryIcon);
            var textCategory = view?.FindViewById<TextView>(Resource.Id.textCategory);
            var textDescription = view?.FindViewById<TextView>(Resource.Id.textDescription);
            var textDate = view?.FindViewById<TextView>(Resource.Id.textDate);
            var textAmount = view?.FindViewById<TextView>(Resource.Id.textAmount);

            if (textCategoryIcon != null)
            {
                textCategoryIcon.Text = transaction.Type == TransactionType.Income ? "💰" : "💸";
            }

            if (textCategory != null)
                textCategory.Text = transaction.CategoryName;

            if (textDescription != null)
            {
                textDescription.Text = string.IsNullOrWhiteSpace(transaction.Description)
                    ? "无描述"
                    : transaction.Description;
            }

            if (textDate != null)
                textDate.Text = transaction.Date.ToString("yyyy-MM-dd");

            if (textAmount != null)
            {
                string prefix = transaction.Type == TransactionType.Income ? "+" : "-";
                textAmount.Text = $"{prefix}¥{transaction.Amount:N2}";
                
                var color = transaction.Type == TransactionType.Income
                    ? Android.Graphics.Color.ParseColor("#4CAF50")
                    : Android.Graphics.Color.ParseColor("#F44336");
                textAmount.SetTextColor(color);
            }

            return view;
        }
    }
}

